package com.ctrl.riveradministrator.mvp.presenter;

import android.content.Context;
import android.content.pm.PackageManager;

import com.ctrl.riveradministrator.base.BaseObserver;
import com.ctrl.riveradministrator.base.BasePresenter;
import com.ctrl.riveradministrator.RaApplication;
import com.ctrl.riveradministrator.mvp.model.Version;
import com.ctrl.riveradministrator.mvp.view.activity.main.MainView;

import java.util.HashMap;
import java.util.List;

public class MainPresenter extends BasePresenter<MainView> {

    public MainPresenter(MainView baseView) {
        super(baseView);
    }

    public void checkUpdate() {
        HashMap map = new HashMap();
        attachView(apiServiceURL.checkVersion(map), new BaseObserver<Version>(getBaseView()) {

            @Override
            public void onSuccess(Version model) {
                int versionCode = model.getAppVersionNo();
                String appVersion = model.getAppVersion();
                String fileName = model.getFileName();
                boolean force = model.isForce();
                String appUpdateDescription = model.getAppUpdateDescription();
                if (getVersionCode(RaApplication.raApplication.getApplicationContext()) != versionCode) {
                    getBaseView().onCheckVersion(appVersion, appUpdateDescription, fileName, force);
                }
            }

            @Override
            public void onSuccess(List<Version> model) {

            }

            @Override
            public void onFailed(String msg) {
                getBaseView().onFailed("更新检查失败");
            }

        });
    }

    public static int getVersionCode(Context context) {
        int versionCode1 = 0;
        try {
            if (context.getPackageManager() != null) {
                // 获取软件版本号，对应AndroidManifest.xml下android:versionCode
                versionCode1 = context.getPackageManager().getPackageInfo(
                        getPackageName(context), 0).versionCode;
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode1;
    }

    /**
     * 获取应用的包名
     **/
    public static String getPackageName(Context context) {
        return context.getPackageName();
    }

}
